package com.exam.sacrifice.viewmodel;

import androidx.lifecycle.ViewModel;

import com.exam.commonbiz.base.BasicApplication;
import com.exam.commonbiz.bean.UserInfo;
import com.exam.commonbiz.net.BaseObserver;
import com.exam.commonbiz.net.BaseResponse;
import com.exam.commonbiz.net.ExceptionHandle;
import com.exam.commonbiz.net.XApi;
import com.exam.sacrifice.api.ApiService;
import com.exam.sacrifice.ui.bean.LoginReq;
import com.exam.sacrifice.util.AESUtil;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class LoginViewModel extends ViewModel {

    private ILoginCallBack loginCallBack;

    public void setLoginCallBack(ILoginCallBack loginCallBack) {
        this.loginCallBack = loginCallBack;
    }

    public void login(String phone, String password) {

        LoginReq loginReq = new LoginReq();
        loginReq.phone = phone;
        loginReq.password = AESUtil.encrypt("wq66688820252026", password);

        XApi.get(ApiService.class)
                .login(loginReq)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<UserInfo>() {

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(BaseResponse<UserInfo> response) {
                        if (response.getData() != null){
                            BasicApplication.saveUserInfo(response.getData());
                            BasicApplication.app.setToken(response.getData().token);
                        }

                        if (loginCallBack != null) {
                            loginCallBack.onLoginCallBack();
                        }
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable responeThrowable) {

                    }

                    @Override
                    public void onFinish() {

                    }

                });
    }
}
